package com.lanyan.system.controller.system;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Date;
import java.util.Set;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.lanyan.common.utils.StringUtils;
import com.lanyan.system.domain.*;
import com.lanyan.system.domain.vo.HandleProduct;
import com.lanyan.system.mapper.ClassifyMapper;
import com.lanyan.system.service.ISkuNameService;
import com.lanyan.system.service.ISkuService;
import com.lanyan.system.service.ISkuValueService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.lanyan.common.annotation.Log;
import com.lanyan.common.core.controller.BaseController;
import com.lanyan.common.core.domain.AjaxResult;
import com.lanyan.common.enums.BusinessType;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import com.lanyan.system.service.IProductService;
import com.lanyan.common.utils.poi.ExcelUtil;
import com.lanyan.common.core.page.TableDataInfo;

/**
 * 商品Controller
 *
 * @author lanyan
 * @date 2024-07-27
 */
@RestController
@RequestMapping("/system/product")
public class ProductController extends BaseController
{
    @Autowired
    private IProductService productService;
    @Autowired
    private ISkuNameService skuNameService;
    @Autowired
    private ISkuValueService skuValueService;
    @Autowired
    private ISkuService skuService;
    @Autowired
    private ClassifyMapper classifyMapper;

    /**
     * 查询商品列表
     */
    //@PreAuthorize("@ss.hasPermi('system:product:list')")
    @GetMapping("/list")
    @ApiImplicitParams({
    })
    public TableDataInfo list(Product product)
    {
        startPage();
        List<Product> list = new ArrayList<>();
        //一级分类不为空、二级分类为空
        if (product.getTopClassifyId() != null && product.getClassifyId() == null){
            LambdaQueryWrapper<Classify> classifyLambdaQueryWrapper = new LambdaQueryWrapper<>();
            classifyLambdaQueryWrapper
                    .eq(Classify::getSuperior, product.getTopClassifyId());
            List<Classify> classifies = classifyMapper.selectList(classifyLambdaQueryWrapper);
            Set<Long> collect = classifies.stream().map(Classify::getClassifyId).collect(Collectors.toSet());
            product.setClassIdList(collect);
            list = productService.selectProductListClass(product);
        }else {
            list = productService.selectProductList(product);
        }
        return getDataTable(list);
    }

    /**
     * 导出商品列表
     */
    @PreAuthorize("@ss.hasPermi('system:product:export')")
    @Log(title = "商品", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Product product)
    {
        List<Product> list = productService.selectProductList(product);
        ExcelUtil<Product> util = new ExcelUtil<Product>(Product.class);
        util.exportExcel(response, list, "商品数据");
    }

    /**
     * 获取商品详细信息
     */
    //@PreAuthorize("@ss.hasPermi('system:product:query')")
    @GetMapping(value = "/{productId}")
    public AjaxResult getInfo(@PathVariable("productId") Long productId)
    {
        Product product = productService.getById(productId);
        if (StringUtils.equals(product.getIsMs(),"1")){
            List<SkuName> sns = skuNameService.lambdaQuery()
                    .eq(SkuName::getDelFlag, "0")
                    .eq(SkuName::getProductId, productId)
                    .list();
            for (SkuName sn : sns) {
                List<SkuValue> svs = skuValueService.lambdaQuery()
                        .eq(SkuValue::getDelFlag, "0")
                        .eq(SkuValue::getSkuNameId, sn.getSkuNameId())
                        .list();
                sn.setSvs(svs);
            }
            product.setSns(sns);
        }
        List<Sku> skus = skuService.lambdaQuery()
                .eq(Sku::getDelFlag, "0")
                .eq(Sku::getProductId, productId)
                .list();
        product.setSkus(skus);
        Integer classifyIdOne = product.getClassifyIdOne();
        Integer classifyIdTwo = product.getClassifyIdTwo();
        product.setTopClassifyIdOne(classifyMapper.selectById(classifyIdOne).getSuperior());
        product.setTopClassifyIdTwo(classifyMapper.selectById(classifyIdTwo).getSuperior());

        return success(product);
    }

    /**
     * 新增商品
     */
    //@PreAuthorize("@ss.hasPermi('system:product:add')")
    @Log(title = "商品", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiImplicitParams({
    })
    public AjaxResult add(@RequestBody Product product)
    {
        product.setStock(0L);
        product.setCreateTime(new Date());
        product.setMarketPrice(BigDecimal.ZERO);
        productService.save(product);
        List<SkuName> sns = product.getSns();
        if (sns != null){
            for (SkuName sn : sns) {
                sn.setProductId(product.getProductId());
                skuNameService.saveOrUpdate(sn);
                List<SkuValue> svs = sn.getSvs();
                if (svs != null){
                    for (SkuValue sv : svs) {
                        sv.setSkuNameId(sn.getSkuNameId());
                        sv.setProductId(product.getProductId());
                        skuValueService.saveOrUpdate(sv);
                    }
                }
            }
        }
        List<Sku> skus = product.getSkus();
        if (skus != null){
            BigDecimal min = null;
            BigDecimal max = null;
            for (Sku sku : skus) {
                if (min == null){
                    min = sku.getPrice();
                    max = sku.getPrice();
                }else if (min.compareTo(sku.getPrice()) > 0){
                    min = sku.getPrice();
                }else if (max.compareTo(sku.getPrice()) < 0){
                    max = sku.getPrice();
                }
                if (sku.getMarketPrice().compareTo(product.getMarketPrice()) > 0){
                    product.setMarketPrice(sku.getMarketPrice());
                }
                sku.setProductId(product.getProductId());
                skuService.saveOrUpdate(sku);
                product.setStock( product.getStock() + sku.getStock());
            }
/*            if (min.compareTo(max) == 0){
                product.setPrice("¥"+min);
            }else {
                product.setPrice("¥"+min+"~"+"¥"+max);
            }*/
            product.setPrice(String.valueOf(min));
            productService.updateById(product);
        }
        return success("新增成功");
    }

    /**
     * 修改商品
     */
    @PreAuthorize("@ss.hasPermi('system:product:edit')")
    @Log(title = "商品", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "名称", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "mainImg", value = "主图", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "swiperImg", value = "轮播图", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "classifyId", value = "所属分类", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "price", value = "拼团价", dataType = "BigDecimal", dataTypeClass = BigDecimal.class),
            @ApiImplicitParam(name = "fixedPrice", value = "一口价", dataType = "BigDecimal", dataTypeClass = BigDecimal.class),
            @ApiImplicitParam(name = "marketPrice", value = "一口会员价", dataType = "BigDecimal", dataTypeClass = BigDecimal.class),
            @ApiImplicitParam(name = "stock", value = "库存", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "accomplish", value = "已拼数量", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "accomplishFalse", value = "虚拟已拼数量", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "minNum", value = "最小起订量", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "details", value = "详情", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "freightId", value = "运费模板id", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "freightPrice", value = "运费", dataType = "BigDecimal", dataTypeClass = BigDecimal.class),
            @ApiImplicitParam(name = "isCommend", value = "是否推荐", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "needPeople", value = "成团需要单数", dataType = "Integer", dataTypeClass = Integer.class),
            @ApiImplicitParam(name = "loseTime", value = "失效时间小时", dataType = "Integer", dataTypeClass = Integer.class),
            @ApiImplicitParam(name = "productSort", value = "排序值", dataType = "Integer", dataTypeClass = Integer.class),
    })
    public AjaxResult edit(@RequestBody Product product)
    {
        productService.updateById(product);
        List<SkuName> sns = product.getSns();
        if (sns != null && sns.size() != 0){
            skuNameService.lambdaUpdate().eq(SkuName::getProductId,product.getProductId()).set(SkuName::getDelFlag,"1").update();
            skuValueService.lambdaUpdate().eq(SkuValue::getProductId,product.getProductId()).set(SkuValue::getDelFlag,"1").update();
            for (SkuName sn : sns) {
                sn.setProductId(product.getProductId());
                sn.setDelFlag("0");
                skuNameService.saveOrUpdate(sn);
                List<SkuValue> svs = sn.getSvs();
                if (svs != null){
                    for (SkuValue sv : svs) {
                        sv.setDelFlag("0");
                        sv.setSkuNameId(sn.getSkuNameId());
                        sv.setProductId(product.getProductId());
                        skuValueService.saveOrUpdate(sv);
                    }
                }
            }
        }
        List<Sku> skus = product.getSkus();
        if (skus != null && skus.size() != 0){
            skuService.lambdaUpdate().eq(Sku::getProductId,product.getProductId()).set(Sku::getDelFlag,"1").update();
            BigDecimal min = null;
            BigDecimal max = null;
            product.setStock(0L);
            for (Sku sku : skus) {
                if (min == null){
                    min = sku.getPrice();
                    max = sku.getPrice();
                }else if (min.compareTo(sku.getPrice()) > 0){
                    min = sku.getPrice();
                }else if (max.compareTo(sku.getPrice()) < 0){
                    max = sku.getPrice();
                }
                if (sku.getMarketPrice().compareTo(product.getMarketPrice()) > 0){
                    product.setMarketPrice(sku.getMarketPrice());
                }
                sku.setDelFlag("0");
                sku.setProductId(product.getProductId());
                skuService.saveOrUpdate(sku);
                product.setStock( product.getStock() + sku.getStock());
            }
            product.setPrice(String.valueOf(min));
            productService.lambdaUpdate()
                    .eq(Product::getProductId,product.getProductId())
                    .set(Product::getStock,product.getStock())
                    .set(Product::getPrice,product.getPrice())
                    .set(Product::getMarketPrice,product.getMarketPrice())
                    .update();
        }
        return success("修改成功");
    }

    /**
     * 删除商品
     */
    @PreAuthorize("@ss.hasPermi('system:product:remove')")
    @Log(title = "商品", businessType = BusinessType.DELETE)
    @DeleteMapping("/{productIds}")
    public AjaxResult remove(@PathVariable Long[] productIds)
    {
        return toAjax(productService.deleteProductByProductIds(productIds));
    }

    @PostMapping("/handleSwitch")
    @ResponseBody
    public AjaxResult handleSwitch(@RequestBody HandleProduct handleProduct)
    {
        LambdaUpdateChainWrapper<Product> wrapper = productService.lambdaUpdate();
        if (StringUtils.equals(handleProduct.getType(), "0")){
            //推荐
            wrapper.set(Product::getIsCommend,handleProduct.getIsTrue());
        }else if (StringUtils.equals(handleProduct.getType(), "-1")){
            //删除
            wrapper.set(Product::getDelFlag,"1");
        }else if (StringUtils.equals(handleProduct.getType(), "2")){
            //必须支付
            wrapper.set(Product::getNeedPay,handleProduct.getIsTrue());
        }else {
            //售卖
            wrapper.set(Product::getIsSale,handleProduct.getIsTrue());
        }
        wrapper.in(Product::getProductId,handleProduct.getIds())
                .update();
        return success();
    }

    /**
     * 获取商品统计
     */
    @GetMapping("/getSum")
    public TableDataInfo getSum(String startTime,String endTime)
    {
        startPage();
        List<Product> list = productService.getSum(startTime, endTime);
        return getDataTable(list);
    }
}
